define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'city-picker', 'city-picker-data'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            //重写添加和编辑框的大小
            $(".btn-add").data("area", ["50%", "85%"]);
            $(".btn-edit").data("area", ["50%", "88%"]);

            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'shop/shop/index' + location.search,
                    add_url: 'shop/shop/add',
                    edit_url: 'shop/shop/edit',
                    del_url: 'shop/shop/del',
                    multi_url: 'shop/shop/multi',
                    import_url: 'shop/shop/import',
                    table: 'shop',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                singleSelect: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('店铺名称'), operate: 'LIKE', align: 'left'},
                        {field: 'supervision.name', title: __('督导'), operate: 'LIKE'},
                        {field: 'shop.mobile', title: __('商家手机号'), operate: 'LIKE', visible: false},
                        {field: 'mobile', title: __('商家手机号'), operate: false},
                        {field: 'ratio', title: __('手续费'), operate: false},
                        {
                            field: 'shop.status',
                            title: __('店铺状态'),
                            searchList: {"1": __('试营业'), "2": __('营业中'), "3": __('筹备中'), "4": __('休息中')},
                            formatter: function (value,row,index) {
                                //console.log(row.status);
                                var statusVal = row.status;
                                if (statusVal === '1') {
                                    return '试营业';
                                } else if (statusVal === '2') {
                                    return '营业中';
                                } else if (statusVal === '3') {
                                    return '筹备中';
                                } else if (statusVal === '4') {
                                    return '休息中';
                                } else {
                                    return '其他';
                                }
                            }
                        },
                        {
                            field: 'shop_type',
                            title: __('店铺类型'),
                            searchList: {
                                "棋牌": __('棋牌'),
                                "台球": __('台球'),
                                "棋牌台球": __('棋牌台球'),
                                "台球棋牌": __('台球棋牌')
                            },
                        },
                        {field: 'ref_name', title: __('代理商'), operate: false},
                        {field: 'ref_mobile', title: __('代理商手机号')},
                        {field: 'agent_ratio', title: __('代理商手续费'), operate: false},
                        {field: 'city', title: __('城市'), operate: 'LIKE'},
                        {field: 'is_join_balance', title: __('开通平台余额'), searchList: {"1": __('已开通'), "-1": __('未开通')},},
                        {
                            field: 'address', title: __('地址'), operate: false, align: 'left',
                            formatter: function (value, row, index, field) {
                                if (value == null) {
                                    return "";
                                }
                                return "<span style='display: block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;' title='" + row.address + "'>" + value + "</span>";
                            },
                            cellStyle: function (value, row, index, field) {
                                return {
                                    css: {
                                        "white-space": "nowrap",
                                        "text-overflow": "ellipsis",
                                        "overflow": "hidden",
                                        "max-width": "300px"
                                    }
                                };
                            }
                        },
                        {
                            field: 'logo',
                            title: __('Logo'),
                            events: Table.api.events.image,
                            formatter: Table.api.formatter.image,
                            operate: false
                        },
                        {field: 'tel', title: __('客服电话'), operate: 'LIKE'},
                        {
                            field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,

                            buttons: [
                                {
                                    name: 'list',
                                    title: __('包厢管理'),
                                    text: '包厢管理',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: function (row) {
                                        return "shop/shoproom/index?shop_id=" + row['id'];
                                    }
                                },

                                {
                                    name: 'list',
                                    title: __('订单列表'),
                                    text: '订单列表',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: function (row) {
                                        return "order/shoporder/index?shop_id=" + row['id'];
                                    }
                                },

                                {
                                    name: 'list',
                                    title: __('充值管理'),
                                    text: '充值订单',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: function (row) {
                                        return "shop/shopcharge/index?shop_id=" + row['id'];
                                    }
                                },
                                {
                                    name: 'list',
                                    title: __('充值配置'),
                                    text: '充值配置',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: function (row) {
                                        return "shop/shopchargeconfig/index?shop_id=" + row['id'];
                                    }
                                },


                                {
                                    name: 'list',
                                    title: __('预定列表'),
                                    text: '预定列表',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: function (row) {
                                        return "shop/shoproombook/index?shop_id=" + row['id'];
                                    }
                                },

                                {
                                    name: 'list',
                                    title: __('店铺员工'),
                                    text: '店铺员工',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: function (row) {
                                        return "shop/shopstaff/index?shop_id=" + row['id'];
                                    }
                                },
                                {
                                    name: 'list',
                                    title: __('包厢套餐'),
                                    text: '包厢套餐',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: function (row) {
                                        return "shop/shoproomset/index?shop_id=" + row['id'];
                                    }
                                },
                                {
                                    name: 'list',
                                    title: __('资金流水'),
                                    text: '资金流水',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: function (row) {
                                        return "money/shoporderprofit/index?shop_id=" + row['id'];
                                    }
                                },


                            ],
                            formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true);
                                $(table).data("operate-del", null);
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }
                        }
                    ]
                ]
            });

            table.on('post-body.bs.table', function () {
                $(".btn-editone").data("area", ["50%", "88%"]);
                $(".btn-addone").data("area", ["50%", "85%"]);
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            $('#check_mobile').on('click', function (event) {
                event.preventDefault();//阻止表单发起默认请求
                const inputMobile = $('#c-mobile').val();
                // console.log('点击获取用户操作值：' + inputMobile);
                if (inputMobile === "") {
                    alert('手机号码不能为空');
                } else {
                    layer.msg('加载中...', {icon: 16, shade: 0.01, time: 10 * 1000});
                    //console.log('获取输入框的值为：' + firstIput);
                    getUser(inputMobile);
                    layer.closeAll();
                }
            });

            //查询saas用户
            function getUser(mobile) {
                $.ajax({
                    type: "post",
                    url: "/admin/shop/shop/getUser",
                    async: true,
                    data: {'mobile': mobile},
                    success: function (res) {
                        if (res.code === 0) {
                            alert(res.msg);
                        } else {
                            alert('用户uid为：【' + res.data + '】');
                        }
                    },
                    error: function (res) {
                        alert('查询失败');
                    }
                });
            };

            Controller.api.bindevent();
        },
        edit: function () {
            const $cityInput = $("#c-city");
            const $cityVal = $("#city_val");
            const cityName = $cityVal.val().trim();

            // 前提检查
            if (typeof ChineseDistricts === 'undefined') {
                console.error('❌ 未加载ChineseDistricts数据');
                return;
            }
            if (typeof $cityInput.citypicker !== 'function') {
                console.error('❌ 未加载citypicker插件');
                return;
            }

            if ($cityInput.data('citypicker')) {
                $cityInput.citypicker('destroy');
            }
            $cityInput.val(''); // 清空原有值

            // 查找城市对应的省份和编码（不变，确保匹配正确）
            function findProvinceAndCity(cityName) {
                const normalizedCity = cityName.replace(/市$/, '').trim();
                let result = { province: '', city: '', provinceCode: '', cityCode: '' };

                const provinces = ChineseDistricts[86];
                for (const groupKey in provinces) {
                    if (!provinces.hasOwnProperty(groupKey)) continue;

                    const provinceGroup = provinces[groupKey];
                    for (let i = 0; i < provinceGroup.length; i++) {
                        const province = provinceGroup[i];
                        const pCode = province.code;
                        const pName = province.address;

                        if (ChineseDistricts[pCode]) {
                            for (const cCode in ChineseDistricts[pCode]) {
                                if (!ChineseDistricts[pCode].hasOwnProperty(cCode)) continue;

                                const cName = ChineseDistricts[pCode][cCode];
                                const normalizedCName = cName.replace(/市$/, '').trim();

                                if (normalizedCName === normalizedCity) {
                                    result = {
                                        province: pName,
                                        city: cName,
                                        provinceCode: pCode,
                                        cityCode: cCode
                                    };
                                    return result;
                                }
                            }
                        }
                    }
                }
                return result;
            }

            const locationData = findProvinceAndCity(cityName);
            console.log('匹配结果：', locationData); // 必须有 provinceCode 和 cityCode！

            const cityPicker = $cityInput.citypicker({
                level: 'city' // 只传级别，其他参数不加
            });

            cityPicker.citypicker('setVal', [locationData.provinceCode, locationData.cityCode]);
            console.log('用编码回填：', [locationData.provinceCode, locationData.cityCode]);

            $cityInput.val(`${locationData.province}/${locationData.city}`);
            cityPicker.citypicker('refresh');


            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
